import { Injectable } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { ConfigProvider } from "../config/config";
import { UtilsProvider } from "../utils/utils";

@Injectable()
export class UrlProvider {
    ownerUser;
    constructor(
        public browserCtrl: InAppBrowser,
        public config: ConfigProvider,
        public util: UtilsProvider
    ) {

    }

    getUrlParams() {
        let addressUrl = location.search.slice(1);//取参数        
        return new URLSearchParams(addressUrl);
    }

    getParam(key) {
        let UrlParams = this.getUrlParams();
        return UrlParams.get(key);
    }

    jumpUrl(url) {
        if (url == 'javascript:void(0);') {
            return false;
        }
        location.href = url;
    }
    // 获取链接中的参数 区分catalog_id和id
    GetQueryString(name) {
        let link = location.search.replace(/@/g,"&");
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = link.substr(1).match(reg);
        if (r != null) return decodeURIComponent(r[2]); return null;
    }

    getShareUrl(page, data, userId) {
        let token = this.config.getToken();
        let currHash = location.hash;
        let shareUserList = [];
        
        if (JSON.parse(this.GetQueryString('data'))) {
            if (JSON.parse(this.GetQueryString('data')) == data.id) {
                
                // 判断是否是同一条信息
                if (this.GetQueryString('userId')) {
                    // 判断是否存在转发用户
                    shareUserList = this.GetQueryString('userId').split(',');
                    if (shareUserList.indexOf(String(userId)) > -1) {
                        // 判断是否已经转发过 
                        shareUserList = shareUserList;
                    } else {
                        if (shareUserList.length < 2) {
                            // 转发用户只有最后两位有佣金
                            shareUserList.push(String(userId))
                        } else {
                            shareUserList.shift()
                            shareUserList.push(String(userId))
                        }
                    }
                } else {
                    this.ownerUser = userId;
                    shareUserList.push(String(userId))
                }
            } else {
                shareUserList = [];
                shareUserList.push(String(userId))
            }
        } else {
            shareUserList.push(String(userId))
        }
        //
        let params = "?share_token=" + token + "&page=" + page + '&data=' + data.id + '&userId=' + shareUserList;
        return this.config.webUrl + '/' + params + currHash;
    }

}
